package com.bdqn.tour.servlet.Tj;

import com.bdqn.tour.pojo.Ticket;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.bdqn.tour.service.TicketService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeParseException;
import java.util.*;

@WebServlet("/search-tickets")
public class SearchTicketsServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private Connection connection;
    private static final Logger logger = LoggerFactory.getLogger(SearchTicketsServlet.class);
    private TicketService ticketService = new TicketService(); // 创建 TicketService 实例

    @Override
    public void init() throws ServletException {
        super.init();
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/tourproject", "root", "123456");
        } catch (ClassNotFoundException | SQLException e) {
            throw new ServletException(e);
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");


        try {
            // 记录请求的表单数据
            Map<String, String[]> parameterMap = request.getParameterMap();
            StringBuilder paramsStringBuilder = new StringBuilder();
            for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) {
                String key = entry.getKey();
                String[] values = entry.getValue();
                if (values != null && values.length > 0) {
                    paramsStringBuilder.append(key).append("=").append(String.join(",", values)).append(", ");
                }
            }
            String logMessage = paramsStringBuilder.toString().trim().replaceAll(", $", "");
            logger.info("Received POST request parameters: {}", logMessage);

            // 获取请求参数
            String departureCity = getRequiredParameter(request, "departureCity");
            String destination = getRequiredParameter(request, "destination");
            String departureDate = getRequiredParameter(request, "departureDate");
            String returnDate = request.getParameter("returnDate");
            String type = request.getParameter("trip-type"); // 单程还是返程
            String tripType = getRequiredParameter(request, "tripType"); // 车票类型(机票/火车票/汽车票)
            boolean hasChild = Boolean.parseBoolean(request.getParameter("hasChild"));
            boolean hasInfant = Boolean.parseBoolean(request.getParameter("hasInfant"));

            // 其他参数校验
            if ("return".equals(type) && (returnDate == null || returnDate.isEmpty())) {
                throw new IllegalArgumentException("缺少返回日期参数");
            }

            // 获取车次信息
            TicketService ticketService = new TicketService(connection); // 确保传入数据库连接
            List<Ticket> tickets = ticketService.getTickets(type, tripType, departureCity, destination, departureDate, returnDate, hasInfant, hasChild);

            // 构建 JSON 响应
            JSONObject jsonResponse = new JSONObject();
            if (!tickets.isEmpty()) {
                String uniqueSearchId = UUID.randomUUID().toString();
                HttpSession session = request.getSession();
                session.setAttribute("searchId", uniqueSearchId);
                session.setAttribute("tickets", tickets);
                jsonResponse.put("success", true);
                jsonResponse.put("searchId", uniqueSearchId);
                String redirectUrl = "view_available_tickets.jsp?searchId=" + uniqueSearchId + "&departureCity=" + departureCity + "&destination=" + destination + "&departureDate=" + departureDate;
                jsonResponse.put("redirect", redirectUrl);
                logger.info("Returning JSON response: {}", jsonResponse.toString());
            } else {
                jsonResponse.put("success", false);
                jsonResponse.put("message", "未找到符合条件的车票");
                jsonResponse.put("redirect", "no_results.jsp");
            }

            // 设置响应头并写入 JSON 响应
            response.setStatus(HttpServletResponse.SC_OK);
            PrintWriter out = response.getWriter();
            out.print(jsonResponse.toString());
            out.flush();
            out.close(); // 确保关闭输出流

        } catch (IllegalArgumentException e) {
            sendErrorResponse(response, HttpServletResponse.SC_BAD_REQUEST, "请求参数错误: " + e.getMessage());
        } catch (DateTimeParseException e) {
            sendErrorResponse(response, HttpServletResponse.SC_BAD_REQUEST, "日期格式错误，请使用 YYYY-MM-DD 格式");
        } catch (Exception e) {
            logger.error("Unexpected error occurred: {}", e.getMessage(), e);
            sendErrorResponse(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "服务器内部错误，请稍后再试");
        }
    }


    private String getRequiredParameter(HttpServletRequest request, String name) throws IllegalArgumentException {
        String value = request.getParameter(name);
        if (value == null || value.trim().isEmpty()) {
            throw new IllegalArgumentException("缺少参数: " + name);
        }
        return value;
    }

    private void sendErrorResponse(HttpServletResponse response, int status, String message) throws IOException {
        response.setStatus(status);
        PrintWriter out = response.getWriter();
        JSONObject errorResponse = new JSONObject();
        errorResponse.put("success", false);
        errorResponse.put("message", message);
        out.print(errorResponse.toString());
        out.flush();
    }
}
